package cn.iocoder.yudao.module.erp.service.departquantity;

import cn.iocoder.yudao.module.system.controller.admin.dept.vo.dept.DeptListReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.dept.DeptDO;
import cn.iocoder.yudao.module.system.dal.mysql.dept.DeptMapper;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.iocoder.yudao.module.erp.controller.admin.departquantity.vo.*;
import cn.iocoder.yudao.module.erp.dal.dataobject.departquantity.DepartQuantityDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.erp.dal.mysql.departquantity.DepartQuantityMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.erp.enums.ErrorCodeConstants.*;

/**
 * 带量分配 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class DepartQuantityServiceImpl implements DepartQuantityService {

    @Resource
    private DepartQuantityMapper departQuantityMapper;
    @Resource
    private DeptMapper deptMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createDepartQuantity(DepartQuantitySaveReqVO createReqVO) {
        // 插入
        DepartQuantityDO departQuantity = BeanUtils.toBean(createReqVO, DepartQuantityDO.class);
        departQuantityMapper.insert(departQuantity);
        // 返回
        return departQuantity.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDepartQuantity(DepartQuantitySaveReqVO updateReqVO) {
        // 校验存在
        validateDepartQuantityExists(updateReqVO.getId());
        // 更新
        DepartQuantityDO updateObj = BeanUtils.toBean(updateReqVO, DepartQuantityDO.class);
        departQuantityMapper.updateById(updateObj);

        // 更新子表
        updateDeptList(updateReqVO.getId(), updateReqVO.getDepts());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteDepartQuantity(Long id) {
        // 校验存在
        validateDepartQuantityExists(id);
        // 删除
        departQuantityMapper.deleteById(id);

        // 删除子表
        deleteDeptById(id);
    }

    private void validateDepartQuantityExists(Long id) {
        if (departQuantityMapper.selectById(id) == null) {
            throw exception(DEPART_QUANTITY_NOT_EXISTS);
        }
    }

    @Override
    public DepartQuantityDO getDepartQuantity(Long id) {
        return departQuantityMapper.selectById(id);
    }

    @Override
    public PageResult<DepartQuantityDO> getDepartQuantityPage(DepartQuantityPageReqVO pageReqVO) {
        return departQuantityMapper.selectPage(pageReqVO);
    }
    @Override
    public List<DeptDO> getDeptPage(DeptListReqVO pageReqVO) {
       List<DeptDO> dp = departQuantityMapper.getDeptPage(pageReqVO);
       List<DepartQuantityDO> dq = departQuantityMapper.seletDepartQuantity(pageReqVO.getId());
       for(DepartQuantityDO dqD : dq){
           for(DeptDO dd :dp){
               if(dqD.getDeptId().equals(dd.getId())){
                    dd.setCount(dqD.getCount());
               }
           }
       }
        return dp;
    }

    @Override
    public List<DepartQuantityRespVO> getQuantity(Long id) {
        return departQuantityMapper.getQuantity(id);
    }

    @Override
    public List<String> selectForProduct(Long productId) {
        return departQuantityMapper.selectForProduct(productId);
    }

    @Override
    public void deleteForProduct(Long productId) {
        departQuantityMapper.deleteForProduct(productId);
    }
    // ==================== 子表（部门） ====================

    @Override
    public List<DeptDO> getDeptListById(Long id) {
        return deptMapper.selectListById(id);
    }



    private void createDeptList(Long id, List<DeptDO> list) {
        list.forEach(o -> o.setId(id));
        deptMapper.insertBatch(list);
    }

    private void updateDeptList(Long id, List<DeptDO> list) {
        deleteDeptById(id);
		list.forEach(o -> o.setId(null).setUpdater(null).setUpdateTime(null)); // 解决更新情况下：1）id 冲突；2）updateTime 不更新
        createDeptList(id, list);
    }

    private void deleteDeptById(Long id) {
        deptMapper.deleteById(id);
    }

}